package com.yy.job.core.run;

import java.util.HashMap;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.yy.job.core.config.JobConfigXmlContext;
import com.yy.job.core.config.xml.ModuleXmlConfig;
import com.yy.job.core.run.worker.ModuleWorker;

/**
 * YY-JOB启动监听器<br>
 * 根据xml配置,启动moduleBoss,每个moduleBoss里面根据jobWorkerSize创建对应数量的jobWorker
 * 
 * @author eleven.li
 *
 */
@Component
public class JobApplicationStartListener implements ApplicationListener<ApplicationReadyEvent> {

	private static final Logger log = LoggerFactory.getLogger(JobApplicationStartListener.class);
	
	/**
	 * 标记位，避免启动两次
	 */
	private boolean listenerStarted = false;
	
	private HashMap<String, ModuleWorker> modulWorkerMap = Maps.newHashMap();
	
	@Autowired
	private JobConfigXmlContext jobConfigXmlContext;
	
	@Override
	public void onApplicationEvent(ApplicationReadyEvent event) {
		
		synchronized (this) {
			// 避免加载两次
			if (listenerStarted) {
				return;
			}
			log.info("yy-job JobApplicationStartListener is starting ... ");
			if(jobConfigXmlContext.getProjectXmlConfig() == null) {
				log.warn("projectXmlConfig is null, do not start yy-job...");
				return;
			}
			// Module配置，如果没配置的话，不用启动
			List<ModuleXmlConfig> moduleConfigs = jobConfigXmlContext.getProjectXmlConfig().getModuleConfigs();
			if(CollectionUtils.isEmpty(moduleConfigs)) {
				log.warn("moduleConfigs is null, do not start yy-job...");
			}
			
			// 根据Xml配置，启动本地moduleWorder
			for (ModuleXmlConfig moduleJobConfig : moduleConfigs) {
				if(moduleJobConfig.getModuleWorker() != null) {
					continue;
				}
		
				// 初始化并启动moduleWorker
				ModuleWorker moduleWorker = new ModuleWorker(jobConfigXmlContext.getProjectXmlConfig().getProjectCode(),moduleJobConfig);
				this.modulWorkerMap.put(moduleJobConfig.getModuleCode(), moduleWorker);
				moduleWorker.start();
			}
			this.listenerStarted = true;
			
			log.info("yy-job JobApplicationStartListener started successful ... ");
		}
	}

	public HashMap<String, ModuleWorker> getModulWorkerMap() {
		return modulWorkerMap;
	}

}
